import axios from "axios";
import { message } from "ant-design-vue";

const serializeGetParams = (params = {}) => {
  const searchParams = new URLSearchParams(params);
  return searchParams.toString();
};

const instance = axios.create({
  baseURL: "/",
  timeout: 100000,
  responseType: "json",
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    if (response.status >= 200 && response.status < 300) {
      return response.data;
    }
    message.error(response?.statusText || "请求失败");
    return Promise.reject(response);
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

const get = (url, params = {}) =>
  instance.get(`${url}?${serializeGetParams(params)}`);

const post = (url, params = {}) =>
  instance.post(url, params, {
    headers: {
      contentType: "application/json",
    },
  });

export { get, post };
